var rotateImgTimeoutId = 0;
var mainPage = 'mainPage';
var rotatingImgList = []; 
function stopRotating() {
	clearTimeout(rotateImgTimeoutId);
}
function startRotating() {
	startRotatingWithTimeOut(1);
}
function startRotatingWithTimeOut(timeOut) {
	stopRotating();
	rotateImgTimeoutId = setTimeout(rotateImg, timeOut);
}

function rotateImg() {
	if($('#rotatingImg')){
		var index = Math.floor(Math.random()*rotatingImgList.length);
		var newConent = rotatingImgList[index];
		while(newConent && newConent.img==$('#rotatingImg').attr('src')){
			index = Math.floor(Math.random()*rotatingImgList.length)
			newConent = rotatingImgList[index]
		}
		if(!newConent) return;
		var imgLoad = $("<img />");
		imgLoad.attr("src", newConent.img);
		imgLoad.unbind("load");
		imgLoad.bind("load", function () {
			var _height = this.height;
			var _width = this.width;
			var img_box = $(".imgBox");
			var rotating_img_msg = $("#rotating_img_msg");
			rotating_img_msg.animate({opacity: 0}, 1, function() {
				rotating_img_msg.css('min-height', '0px');
				rotating_img_msg.html(newConent.description);
				var boxHeight = parseInt(img_box.css('height'));
				var boxWidth = parseInt(img_box.css('width'));
				var msgBoxHeight = parseInt(rotating_img_msg.css('height'));
				rotating_img_msg.css('min-height', msgBoxHeight+'px');
				rotating_img_msg.css('margin-top', (-(msgBoxHeight+25)) + 'px');
				rotating_img_msg.css('margin-left', '20px');
				rotating_img_msg.css('width', (boxWidth-40)+'px');
				
				rotating_img_msg.html('');
				
				rotating_img_msg.animate({opacity: 1}, 1);
				var rotating_img = $('#rotatingImg')
				rotating_img.animate({opacity: 0}, 1000, function() {
					
					this.src = newConent.img;
					rotating_img.unbind("click");
					rotating_img.click(function(){
						console.log(newConent.id);
						ImgBox.open2(newConent.id, rotatingImgList, UserData.isAdmin);
					});
					$(this).animate({opacity: 1}, 1000, function() {
						imScrolling(newConent.description, 10, 0);
						var realH = parseInt(rotating_img.height());//_height*(boxWidth/_width);
						if(realH>boxHeight){
							rotating_img.animate({marginTop: -(realH - boxHeight)}, 6000, function() {
								rotating_img.animate({marginTop: 0}, 2000, function() {
									startRotatingWithTimeOut(2000);
								});
							});
						} else {
							startRotatingWithTimeOut(10000);
						}
					});
				
				});
			});
		});
		
		
	} else {
		stopRotating();
	}
}
function imScrolling(scrollTxt, delay, index, target) {
	if(scrollTxt){
		var exitCode = scrollTxt.length*2;
		while (index < scrollTxt.length && exitCode>0) {
			setTimeout(appendLetter, index * delay, scrollTxt, index);
			index++;
			exitCode--;
		}
	}
}

function appendLetter(scrollTxt, index) {
	$('#rotating_img_msg').append(scrollTxt[index]);
}